﻿using Microsoft.Extensions.DependencyInjection;
using Modules.System.User;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Entity;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Project.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class ProjectCompletedRepository : Repository<ProjectCompleted, DefaultDbContext>
    {
        private readonly IApplicationContext applicationContext;
        public ProjectCompletedRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
            this.applicationContext = applicationContext;
        }

        /// <summary>
        /// author:hzj date:2023/1/2 describe:分页获取完工销户申请
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IPagedList<ProjectCompleted> GetProjectCompleteds(ProjectCompletedQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("project_completed");
            #region 主管单位数据权限
            if (applicationContext.CurrentUser is IDeptUser deptUser && !deptUser.IsSuperAdministrator())
            {
                sql.InnerJoin("project as prj").On($"project_completed.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type=@0 ", deptUser.IndustryType);
                if (deptUser.Level == AdministrativeLevel.City)
                    sql.Append($" and prj.city_code={deptUser.CityCode}");
                if (deptUser.Level == AdministrativeLevel.Area)
                    sql.Append($" and prj.area_code={deptUser.AreaCode}");
            }
            #endregion
            if (query.ProjectId.HasValue)
                sql.Where("project_completed.project_id =@0", query.ProjectId);
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(apply_reason Like @0 or refund_reason Like @0 )", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("project_completed.project_id in (select id from project where name like @0 or prj_num like @0)  ", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.AuditType.HasValue) sql.Where("audit_type = @0 ", query.AuditType);
            sql.OrderBy("project_completed.create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        public bool ExistsByProjectId(int projectId)
        {
            return DbContext.Exists<ProjectCompleted>("project_id=@0", projectId);
        }
    }
}